<template>
  <div style="height:6vh;padding:10px 20px;background-color:#fff;">
    <span style="line-height:60px;font-size:20px;">视频资料</span>
    <el-button type="primary" @click="addNews()"
               style="float: right;margin-top:10px;">发布内容
    </el-button>
  </div>

  <!--视频功能弹窗-->
  <el-dialog :title="dialogTitle"
             v-model="dialogVisible2"
             width="60%"
             :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="10">

        <el-col :span="24" v-if="titleVisible">

          <el-form-item label="标题">
            <el-input placeholder="标题不能少于五个字" v-model="profile1.title" required></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="分类">
            <el-select placeholder="请选择分类" v-model="popCategoryId">
              <!--这个是通过遍历请求后的数组中的数据进行显示的-->
              <el-option v-for="item in categoryList" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!--上传视频按钮-->
        <el-col :span="24">
          <input type="file" @change="handleVideoUpload" :disabled="!isFormValid"/>
        </el-col>

        <el-col :span="24" style="margin-top: 20px;">
          <el-form-item>
            <el-button type="primary" @click="saveVideo">保 存</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>


  <!--搜索卡片-->
  <el-card style="margin: 20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="搜索">
        <el-input placeholder="请输入资料标题" style="width: 220px;" @keydown.enter.prevent="loadProfileList"
                  v-model="keyWords.title"></el-input>
      </el-form-item>

      <el-form-item label="状态" style="width: 290px;">
        <el-select placeholder="请选择状态" v-model="keyWords.status">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="-1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="分类" style="width: 290px;">
        <el-select placeholder="请选择分类" v-model="keyWords.categoryId">
          <el-option v-for="item in categoryList" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="loadProfileList">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>


  <!--列表框-->
  <el-card style="margin: 20px;">
    <el-row :gutter="20" style="width:26%;padding:0 5px 15px 5px;display: inline-block" v-for="item in tableData">
      <el-col :span="24">
        <video controls="" style="width: 300px; height: 190px;">
          <source :src="item.fileUrl" type="video/mp4">
        </video>
        <div>
          <span
              style="border-radius:4px;font-size:12px;border: 1px solid #ff6699;color: #ff6699;padding: 1px 5px 1px 5px;margin-right: 5px;">{{
              item.categoryName
            }}</span>
          <span>{{ item.title }}</span>
        </div>
        <div style="font-size: 12px;margin-top: 5px;">
          <span style="margin-right: 7px;background-color: #fff0e3;color:#ff7f24 ">浏览：{{ item.views }}</span>
          <span style="margin-right: 7px;">{{ item.publisher }} · {{ item.createTime }}</span>
          <span style="float: right;margin-right: 2px;">
            <el-button type="success" size="small" style="--el-button-size:17px;"
                       v-if="item.status == '1'" @click="changeStatus(item.status)">启用</el-button>
            <el-button type="warning" size="small" style="--el-button-size:17px;"
                       v-if="item.status == '-1'">禁用</el-button>
          </span>
        </div>
      </el-col>
    </el-row>
    <div style="margin:30px;float: right;">
      <!--layout="total(总数), sizes(每页总数), prev(上一页), pager(当前页), next(下一页), jumper(跳转页)"
       :pager-count="4" 表示显示4个页码
       :page-sizes="[5, 10, 15, 20]" 表示一共有几个"每页显示多少条"选项
       current-page当前页码 page-size当前页码的条数 total总条数 这三个变量需要和实际数据双向绑定
       :total="400" 表示总条数，需要双向绑定
       @size-change="handleSizeChange" 表示每页显示多少条改变时触发的事件
       @current-change="handleCurrentChange" 表示当前页码改变时触发的事件 -->
      <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 15, 20]"
          v-model:current-page="currentPage"
          v-model:page-size="currentSize"
          v-model:total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
// import { saveAs } from 'file-saver';
import Player from 'xgplayer'
import 'xgplayer/dist/index.min.css'

import {onMounted, ref, watchEffect} from "vue";
import qs from "qs";
import axios from "/src/api/axios";
//定义变量控制文章弹窗是否出现
const dialogVisible1 = ref(false);
//定义变量控制视频弹窗是否出现
const dialogVisible2 = ref(false);
//弹窗名
const dialogTitle = ref('发布内容')
//控制编辑标题的变量
const titleVisible = ref(false);
//控制富文本框的变量
const richTextBox = ref(false);
//控制浏览文章的变量
const browseArticle = ref(false);
//控制视频上传组件的变量
const videoUpload = ref(false);
//控制播放视频的组件的变量
const videoPlayback = ref(false);
//允许点击上传按钮
const allowUpload = ref(true);
//列表以及内容分类
// const type = ref(2);//默认展示的是文章
//获取当前用户数据的功能
const user = ref(getUser());
//管理员权限先默认为true
const admin = ref(true)
//判定当前用户的权限的函数,待定,因为权限现在不明
const isAdmin = (user) => {
  console.log(user)
}
//发布按钮功能
const addNews = () => {
  dialogTitle.value = '发布内容';
  titleVisible.value = true;
  dialogVisible2.value = true;
  videoUpload.value = true;
}

//列表数据
const tableData = ref([]);

//搜索框数据
const keyWords = ref({
  title: '',
  status: '',
  categoryId: '',
  type: '2'//因为是视频了,所以默认是2
});

//点一下启用或者禁用按钮,两者的值就互相发生改变,且改变之后重新查询列表,
const changeStatus = (status) => {
  // if(status == '1'){//如果当前是启用状态,就变成-1
  //   status = '-1';
  // }else {
  //   status = '1';
  // }
}


//弹窗不应该绑定搜索框的分类
const popCategoryId = ref('');

//搜索框的分类列表,这里是通过双向绑定的方式给上到搜索框的keyWords的categoryId
const categoryList = ref([]);
//弹窗的分类列表
const popCategoryList = ref([]);

//查询资料分类
const loadCategoryList = () => {
  // console.log('走这里了吗?走了');
  //查询有视频哪些分类
  // ,{serviceName: 'studyService'}
  axios.get('http://localhost:8091/v1/ems/video/category').then(response => {
    if (response.data.code == 2000) {
      console.log(response);
      categoryList.value = response.data.data;//1,2,3,4,5和分类1,分类2,分类3,分类4,分类5
      popCategoryList.value = response.data.data;
    } else {
      console.log(response.data.message);
    }
  })
}

//查询列表
const loadProfileList = () => {
  //查询条件为标题,状态,视频是什么类型
  console.log(keyWords.value.type);
  console.log(keyWords.value.status);
  keyWords.value.pageSize = currentSize.value;
  keyWords.value.pageNum = currentPage.value;
  let data = qs.stringify(keyWords.value);
  //向后端发起请求获取列表数据
  // {serviceName: 'studyService'}
  axios.get('http://localhost:8091/v1/ems/video/list?' + data).then(response => {
    if (response.data.code == 2000) {
      console.log(response.data.data);
      tableData.value = response.data.data.list;
      console.log(tableData.value);
    } else {
      console.log(response.data.message);
    }
  })
  /*
  tableData.value = [
    {
      'id': 1,
      'title': '视频1',
      'categoryId': 1,
      'categoryName': '分类1',
      'status': '1',
      'statusText': '启用',
      'fileId': 1,
      'fileUrl': '/video/test.mp4',
      'views': 11,
      'publisher': '管路员1',
      'createTime': '2024-01-01 11:22:33',
    },
    {
      'id': 2,
      'title': '视频2',
      'categoryId': 2,
      'categoryName': '分类2',
      'status': '-1',
      'statusText': '禁用',
      'fileId': 1,
      'fileUrl': '/video/test.mp4',
      'views': 10,
      'publisher': '管路员1',
      'createTime': '2024-01-01 11:22:33',
    },
    {
      'id': 3,
      'title': '视频3',
      'categoryId': 3,
      'categoryName': '分类3',
      'status': '1',
      'statusText': '启用',
      'fileId': 1,
      'fileUrl': '/video/test.mp4',
      'views': 12,
      'publisher': '管路员1',
      'createTime': '2024-01-01 11:22:33',
    },
    {
      'id': 4,
      'title': '视频4',
      'categoryId': 4,
      'categoryName': '分类4',
      'status': '1',
      'statusText': '启用',
      'fileId': 1,
      'fileUrl': '/video/test.mp4',
      'views': 13,
      'publisher': '管路员1',
      'createTime': '2024-01-01 11:22:33',
    },
    {
      'id': 5,
      'title': '视频5',
      'categoryId': 5,
      'categoryName': '分类5',
      'status': '1',
      'statusText': '启用',
      'fileId': 1,
      'fileUrl': '/video/test.mp4',
      'views': 14,
      'publisher': '管路员1',
      'createTime': '2024-01-01 11:22:33',
    },
  ];
   */
}
const profile1 = ref({title: '', content: ''})

//编辑的弹窗
/*
const editArticle = (id) => {
  dialogTitle.value = '内容编辑';
  titleVisible.value = true;
  dialogVisible2.value = true;
  videoUpload.value = true;
  //向后端发送请求,将资讯的id传过去,然后获取到标题,内容,然后绑定到弹窗上

  //然后将数据传到profile1中
  profile1.value.title = profile.value[0].title;
  profile1.value.content = profile.value[0].content;
}
 */
//处理弹窗关闭的方法

//关闭弹窗
const handleClose = () => {
  if (confirm('确认要关闭本窗口吗?')) {
    //用户确认关闭后,关闭弹窗
    dialogVisible1.value = false;
    dialogVisible2.value = false;
    titleVisible.value = false;
    richTextBox.value = false;
    browseArticle.value = false;
    videoUpload.value = false;
    videoPlayback.value = false;
  }
}

const deleteArticle = (id) => {
  //发送请求,删除数据库中的数据
  loadProfileList();
}

onMounted(() => {
  // isAdmin(user.value.name);
  // loadProfileList();
  loadCategoryList();
})

const notSupportedMessage = ref('此视频暂无法播放，请稍后再试');

const isFormValid = ref(false); // 控制上传按钮的状态
function validateForm() {
  // 当标题和分类都有值时，设置 isFormValid 为 true
  if (profile1.value.title !== '' && popCategoryId.value !== '') {
    isFormValid.value = true;
  }

}

watchEffect(() => {
  validateForm();
});
const saveData = ref({});
const handleVideoUpload = async (event) => {
  if (isFormValid.value) {
    const file = event.target.files[0];
    console.log(file);
    const formData = new FormData();
    formData.append('file', file);
    console.log(formData);
    try {
      axios.post('/v1/upload/upload', formData, {
        serviceName: 'uploadService',
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }).then((response) => {
        console.log(response.data);
        if (response.data.code === 200) {
          saveData.value.file_id = response.data.data.id;
          console.log(saveData);
          let data = qs.stringify(saveData.value);

        }
      });

    } catch (error) {
      console.error(error);
    }
  } else {
    alert('请先填写标题并选择分类！');
  }
};

const saveVideo = () => {
  axios.post('/v1/ems/video/uploadData', saveData.value, {serviceName: 'studyService'}).then(response => {
    if (response.data.code == 2000) {
      loadProfileList();//重新加载数据
      dialogVisible2.value = false;//弹窗关闭
    }
  })
}


// 获取 input 元素的引用
const refFileInput = ref(null);//获取input元素

//定义变量保存分页器的当前页数
const currentPage = ref(1);
//定义变量保存分页器的每页显示多少条
const currentSize = ref(5);
//定义变量保存数据总条目数
const total = ref(100);
//修改每页显示多少条，触发此函数
const handleSizeChange = (val) => {
  console.log('每页展示' + val + '条数据');
}
//修改当前页码，触发此函数
const handleCurrentChange = (val) => {
  console.log('当前的页数为：' + val);
}

</script>

<style scoped>

</style>